import axios from "axios";
import { ElNotification, ElMessageBox } from 'element-plus'

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

const request = axios.create({
    baseURL: import.meta.env.VITE_REQUEST_BASE_URL,
})

request.interceptors.request.use((config) => {
    const loginInfo = localStorage.getItem('login')
    if (loginInfo) {
        const { access_token } = JSON.parse(loginInfo)
        config.headers.Authorization = `Bearer ${access_token}`
    }

    return config;
}, (error) => {

    return Promise.reject(error);

})


request.interceptors.response.use((response) => {
    if (response.data.code === 200) {
        return response.data
    } else {
        ElNotification({
            title: 'Error',
            message: response.data.message,
            type: 'error',
        })
        return Promise.reject(response.data)
    }
}, (error) => {
    ElNotification({
        title: 'Error',
        message: error.response.data.message,
        type: 'error',
    })
    if (error.response.data.code === 401) {
        localStorage.removeItem('login')
        ElMessageBox.alert('登录状态已更新', '系统提示', {
            confirmButtonText: '重新登录',
            callback: () => {
                location.reload()

            }
        })
    }
    return Promise.reject(error.response.data);
}
)
export default request